/**
 * 
 */
package com.firmye.codereposboot.config.security;

import com.firmye.codereposboot.dao.UserDao;
import com.firmye.codereposboot.model.user.pojo.Role;
import com.firmye.codereposboot.model.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author Firmye
 * @Date 2017年12月7日 上午12:33:55
 * 
 * @Description 2.自定义UserDetailsService
 */
@Component
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	public CustomUserDetailsService() {
		super();
	}

	/**
	 * @Author Firmye
	 * @Date 2017年12月7日 上午12:34:37
	 *
	 * @Description 加载用户信息
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userDao.queryUserByUsername(username);
		if (null == user) {
			throw new UsernameNotFoundException("=====> UserName " + username + " not found");
		}

		log.info("=====> User:" + user);

		List<Role> roles = new ArrayList<>();
		if(null != user.getRoleIds())
			roles = userDao.queryRolesByIds(user.getRoleIds());

		return new CustomUserDetails(user, roles);
	}

}
